<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商户编号" prop="shopId" v-hasRole="['admin']">
        <el-input
          v-model="queryParams.queryName"
          placeholder="请输入商户昵称/手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配送区域" prop="sortArea">
        <el-input
          v-model="queryParams.sortArea"
          placeholder="请输入配配送区域"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isOpen">
        <el-select
          v-model="queryParams.isOpen"
          placeholder="请选择是否启用"
          clearable
          size="small"
        >
          <el-option label="禁用" value="20" />
          <el-option label="启用" value="10" />
        </el-select>
      </el-form-item>
      <el-form-item label="配送点" prop="pointName">
        <el-input
          v-model="queryParams.pointName"
          placeholder="请输入配送点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="pointPhone">
        <el-input
          v-model="queryParams.pointPhone"
          placeholder="请输入配送点手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:point:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:point:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:point:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:point:export']"
          >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pointList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        :index="indexMethod"
        width="50px"
      />
      <el-table-column label="所属商户" align="center" prop="name" />
      <el-table-column label="配送点名称" align="center" prop="pointName" />
      <el-table-column label="省名称" align="center" prop="province" />
      <el-table-column label="城市名称" align="center" prop="city" />
      <el-table-column
        label="手机号码"
        align="center"
        prop="pointPhone"
        width="110"
      />
      <el-table-column label="分拣区域" align="center" prop="sortArea" />
      <el-table-column label="配送点编号" align="center" prop="sortAreaNum" />
      <el-table-column label="区域名称" align="center" prop="area" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="门头照" align="center" prop="pointImg">
        <template slot-scope="scope" v-if="scope.row.pointImg != null">
          <el-image
            :preview-src-list="scope.row.pointImg.split(',')"
            style="width: 30px; height: 30px"
            shape="square"
            :src="image"
            :key="image"
            v-for="image in scope.row.pointImg.split(',')"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="地点经度" align="center" prop="lng" />
      <el-table-column label="地点纬度" align="center" prop="lat" />
      <el-table-column label="是否启用" align="center" prop="isOpen">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.isOpen == '20'">禁用</el-tag>
          <el-tag type="success" v-if="scope.row.isOpen == '10'">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="配送开始时间"
        align="center"
        prop="businessTime"
      />
      <el-table-column label="配送结束时间" align="center" prop="closingTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:point:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:point:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配送点对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配送点名称" prop="pointName">
          <el-input v-model="form.pointName" placeholder="请输入配送点名称" />
        </el-form-item>
        <el-form-item
          label="位置区域"
          prop="province"
          class="distpicker-select"
        >
          <v-distpicker
            :province="form.province"
            :city="form.city"
            :area="form.area"
            @selected="onDistpicker"
          ></v-distpicker>
        </el-form-item>
        <el-form-item label="手机号码" prop="pointPhone">
          <el-input
            style="width: 50%"
            v-model="form.pointPhone"
            placeholder="请输入配送点手机号"
          />
        </el-form-item>
        <el-form-item label="门头照" prop="pointImg">
          <el-upload
            :action="commonUploadApi"
            :accept="'.png,.jpg'"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleSuccess"
          >
            <img v-if="form.pointImg" :src="form.pointImg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="环境照" prop="listImg">
          <el-upload
            list-type="picture-card"
            :multiple="false"
            :action="commonUploadApi"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :headers="headers"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="位置信息" class="location">
          <web-map
            ref="webMap"
            :isDistPoint="true"
            :shopInfo="shopInfo"
            :lng.sync="form.lng"
            :lat.sync="form.lat"
            :address.sync="form.address"
            :scope.sync="distScope"
            :searchOption="{
              city: shopInfo.city,
              citylimit: true,
            }"
            @distArea="getDistArea"
          ></web-map>
        </el-form-item>
        <el-form-item label="分拣区域" prop="sortArea">
          <el-input
            v-model="form.sortArea"
            :readonly="true"
            placeholder="输入位置信息，将会自动分配区域"
          />
        </el-form-item>
        <el-form-item label="自提点编号" prop="sortAreaNum">
          <el-input
            v-model="form.sortAreaNum"
            :readonly="false"
            placeholder="自提点编号"
          />
        </el-form-item>
        <el-form-item label="仓库距离(km)" prop="dis">
          <el-input
            v-model="form.dis"
            :readonly="true"
            placeholder="自提点距离仓库距离"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="isOpen">
          <el-radio-group v-model="form.isOpen">
            <el-radio :label="10">启用</el-radio>
            <el-radio :label="20">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="营业时间" label-width="120px">
          <el-checkbox v-model="checked" @change="handleCheckBox"
            >全日</el-checkbox
          >
          <el-time-select
            placeholder="起始时间"
            v-model="form.businessTime"
            :disabled="checked"
            :picker-options="{
              start: '00:00',
              step: '00:15',
              end: '23:00',
            }"
          >
          </el-time-select>
          -
          <el-time-select
            placeholder="结束时间"
            v-model="form.closingTime"
            :disabled="checked"
            :picker-options="{
              start: '00:01',
              step: '00:15',
              end: '23:59',
            }"
          >
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getShopInfo } from "@/api/system/shop";
import {
  listPoint,
  getPoint,
  delPoint,
  addPoint,
  updatePoint,
  exportPoint,
} from "@/api/system/point";
import WebMap from "@/components/WebMap";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
// svg component
export default {
  components: { WebMap },
  name: "Point",
  data() {
    return {
      shopInfo: {},
      //圈的大小
      distScope: 5,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 配送点表格数据
      pointList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      checked: false,
      dialogImageUrl: "",
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        queryName: undefined,
        isOpen: undefined,
        pointName: undefined,
        province: undefined,
        city: undefined,
        area: undefined,
        address: undefined,
        businessTime: undefined,
        closingTime: undefined,
        delFalg: undefined,
        pointPhone: undefined,
        sortArea: ''
      },
      // 表单参数
      form: {},
      fileList: [],
      headers: { Authorization: "Bearer " + getToken() },
      // 表单校验
      rules: {
        pointName: [
          { required: true, message: "配送点名称不能为空", trigger: "blur" },
        ],
        province: [
          { required: true, message: "配送位置不能为空", trigger: "blur" },
        ],
        businessTime: [
          { required: true, message: "配送开始时间不能为空", trigger: "blur" },
        ],
        closingTime: [
          { required: true, message: "配送结束时间不能为空", trigger: "blur" },
        ],
        isOpen: [
          { required: true, message: "请选择是否开启", trigger: "blur" },
        ],
        sortAreaNum: [
          { required: true, message: "自提点编号不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["commonUploadApi"]),
  },
  created() {
    getShopInfo().then((response) => {
      if (response.code == 200) {
        this.shopInfo = response.data;
      }
    });
    this.getList();
  },
  methods: {
    // getDistArea
    getDistArea(val) {
      console.log(val);
      this.form.dis = val.dis;
      this.form.sortArea = val.area;
    },
    //
    onDistpicker(data) {
      try {
        this.form.province = data.province.value;
        this.form.city = data.city.value;
        this.form.area = data.area.value;
        this.searchOption.city = data.city.value;
      } catch (e) {
        console.log("获取信息异常：" + e);
      }
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.msgError(msg.message);
    },
    handleSuccess(response, file, fileList) {
      console.log(response);
      console.log(this.form);
      this.form.pointImg = response.url;
    },
    handleBeforeRemove(file, fileList) {
      this.form.pointImg = null;
    },
    //筛选
    onDistpicker1(data) {
      try {
        this.queryParams.province = data.province.value;
        this.queryParams.city = data.city.value;
        this.queryParams.area = data.area.value;
        console.log("筛选过后省" + this.queryParams.province);
        console.log("筛选过后市" + this.queryParams.province);
        console.log("筛选过后区" + this.queryParams.province);
      } catch (e) {
        console.log("获取信息异常：" + e);
      }
    },
    //全日
    handleCheckBox() {
      if (this.checked == true) {
        this.form.businessTime = "00:00";
        this.form.closingTime = "23:59";
      } else {
        this.form.businessTime = "";
        this.form.closingTime = "";
      }
    },
    /** 查询配送点列表 */
    getList() {
      this.loading = true;
      listPoint(this.queryParams).then((response) => {
        this.pointList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        shopId: undefined,
        isOpen: undefined,
        pointName: undefined,
        province: this.shopInfo.province,
        city: this.shopInfo.city,
        area: this.shopInfo.area,
        address: this.shopInfo.address,
        lng: this.shopInfo.lng,
        lat: this.shopInfo.lat,
        businessTime: "00:00",
        closingTime: "23:59",
        dis: "",
        delFalg: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        sortAreaNum: "",
        pointImg: "",
        listImg: "",
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配送点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPoint(id).then((response) => {
        this.form = response.data;
        //处理图片
        //图片回显
        this.fileList = [];
        var arr = (this.form.listImg && this.form.listImg.split(",")) || [];
        if (arr.length > 0) {
          arr.forEach((val) => {
            var data = {
              url: val,
              response: {
                url: val,
              },
            };
            this.fileList.push(data);
          });
        }
        this.open = true;
        this.title = "修改配送点";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePoint(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPoint(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      this.form.listImg = undefined;
      fileList.forEach((item) => {
        if (this.form.listImg == undefined) {
          this.form.listImg = item.response.url;
        } else {
          this.form.listImg = this.form.listImg + "," + item.response.url;
        }
      });
    },
    //多图上传成功后的钩子
    uploadSuccess(response, file, fileList) {
      if (this.form.listImg == undefined) {
        this.form.listImg = response.url;
      } else {
        this.form.listImg = this.form.listImg + "," + response.url;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除配送点编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delPoint(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有配送点数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportPoint(queryParams);
        })
        .then((response) => {
          this.download(response.data);
        })
        .catch(function () {});
    },
    /** 序号*/
    indexMethod(index) {
      return (
        index + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
  },
};
</script>
<style scoped>
.distpicker-address-wrapper select {
  padding: 0 !important;
  height: 26px !important;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
  border: 1px solid #c0ccda;
}

.avatar {
  width: 70px;
  height: 70px;
  display: block;
}
</style>
